package me.eg.second;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 811. 子域名访问计数
 *
 * 链接：https://leetcode-cn.com/problems/subdomain-visit-count
 */
public class SubdomainVisits {
    public List<String> subdomainVisits(List<String> cpdomains) {
        Map<String, Integer> map = new HashMap<>();
        for (String cpdomain : cpdomains) {
            String[] visitRecord = cpdomain.split(" ");

            int cnt = Integer.parseInt(visitRecord[0]);
            String[] domains = visitRecord[1].split("\\.");
            String domain = "";
            for (int i = domains.length - 1; i >= 0; i--) {
                if (i == domains.length - 1) domain = domains[i];
                else domain = domains[i] + "." + domain;

                map.put(domain, map.getOrDefault(domain, 0) + cnt);
            }
        }

        List<String> result = new ArrayList<>();
        for (String key : map.keySet()) {
            result.add(map.get(key) + " " + key);
        }
        return result;
    }
}
